function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return [hour, minute, second]
    .map(function(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    })
    .join(':')
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }

  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}
var dateUtils = {
  UNITS: {
    年: 31557600000,
    月: 2629800000,
    天: 86400000,
    小时: 3600000,
    分钟: 60000,
    秒: 1000
  },
  humanize: function(milliseconds) {
    var humanize = ''
    for (var key in this.UNITS) {
      if (milliseconds >= this.UNITS[key]) {
        humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前'
        break
      }
    }
    return humanize || '刚刚'
  },
  humainizeToDay: function(dateStr) {
    var date = this.parse(dateStr)
    var diff = Date.now() - date.getTime()
    if (diff < this.UNITS['天']) {
      return `${this._formatnum(date.getHours())}:${this._formatnum(
        date.getMinutes()
      )}`
    }
    if (this.UNITS['天'] < diff && diff < this.UNITS['天'] * 2) {
      return '昨天'
    }
    return `${this._formatnum(date.getMonth() + 1)}月${this._formatnum(
      date.getDate()
    )}`
  },
  _formatnum: number => {
    return number < 10 ? '0' + number : number
  },
  format: function(dateStr) {
    var date = this.parse(dateStr)
    var diff = Date.now() - date.getTime()
    if (diff < this.UNITS['天']) {
      return this.humanize(diff)
    }
    var _format = function(number) {
      return number < 10 ? '0' + number : number
    }
    return (
      date.getFullYear() +
      '/' +
      _format(date.getMonth() + 1) +
      '/' +
      _format(date.getDate()) +
      '-' +
      _format(date.getHours()) +
      ':' +
      _format(date.getMinutes())
    )
  },

  /**
   *  时间加减，支持三位，两位(按小时来算)，HH:mm:ss , HH:mm
   * @param {String} datetimeStr 8:45:30
   * @param {Object} param1 {h:1,m:30,s:15}
   * @param {String} type   add   sub
   */
  calculateDateTime(datetimeStr, { h = 0, m = 0, s = 0 }, type = 'add') {
    let datelist = datetimeStr.split(':')
    let totalSecond = 0
    let tempSecond = 0
    datelist.forEach((e, index) => {
      totalSecond += e * Math.pow(60, 2 - index)
    })
    tempSecond = h * 60 * 60 + m * 60 + s
    let resultSecond = 0
    switch (type) {
    case 'add':
      resultSecond = totalSecond + tempSecond
      break
    case 'sub':
      resultSecond = totalSecond - tempSecond
      break
    default:
      break
    }
    let resultH = (resultSecond / 3600) % 24 >> 0
    let resultM = ((resultSecond % 3600) / 60) >> 0
    let resultS = (resultSecond % 3600) % 60
    return {
      resultH: resultH < 10 ? '0' + resultH : resultH,
      resultM: resultM < 10 ? '0' + resultM : resultM,
      resultS: resultS < 10 ? '0' + resultS : resultS
    }
  },

  /**
   * 计算两个"HH:mm:ss"格式的字符串的时间差,返回小时
   * @param {String} startstr 21:30
   * @param {String} endstr 01:00
   */
  getDateTimeInterval: function(startstr, endstr) {
    let startTime = startstr
    let endTime = endstr
    let startlist = startTime.split(':')
    let endlist = endTime.split(':')
    if (endlist[0] < startlist[0]) {
      endlist[0] = 24 + Number(endlist[0])
    }
    let starttotal_s = 0
    startlist.forEach((a, index) => {
      if (index == 0) {
        starttotal_s += a * 60 * 60
      }
      if (index == 1) {
        starttotal_s += a * 60
      }
      if (index == 2) {
        starttotal_s += a
      }
    })
    let endtotal_s = 0
    endlist.forEach((a, index) => {
      if (index == 0) {
        endtotal_s += a * 60 * 60
      }
      if (index == 1) {
        endtotal_s += a * 60
      }
      if (index == 2) {
        endtotal_s += a
      }
    })
    let timeInterval = endtotal_s - starttotal_s //秒
    return (timeInterval / 60 / 60).toFixed(2)
  },

  /**
 * 计算"yyyy-mm-dd HH:mm:ss"格式的字符串时间距目前什么时间
 * @param {String} endStr 传入的时间字符串 
 * @returns {any} { d, h, m, s }
 */
  dateTimeRangeNow: function (endStr) {
    endStr=endStr.replace(/-/g,'/')
    let endDate= new Date(endStr)
    return this.formatSeconds ((endDate.getTime()-Date.now())/1000)
  },
  parse: function(str) {
    // 将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
    var a = str.split(/[^0-9]/)
    return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5])
  },
  formatDate: (date, fmt) => {
    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
    // author: meizz
    var o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return fmt
  },
  formatSeconds: value => {
    const result = parseInt(value)
    const d = Math.floor(result / 60 / 60 / 24)
    const h =
      Math.floor((result / 60 / 60) % 24) < 10
        ? '0' + Math.floor((result / 60 / 60) % 24)
        : Math.floor((result / 60 / 60) % 24)
    const m =
      Math.floor((result / 60) % 60) < 10
        ? '0' + Math.floor((result / 60) % 60)
        : Math.floor((result / 60) % 60)
    const s =
      Math.floor(result % 60) < 10
        ? '0' + Math.floor(result % 60)
        : Math.floor(result % 60)
    return { d, h, m, s }
  }
}

/**
 * 构建一个数组    
 * @param {数组长度} length 
 * @returns 数组
 */
function buildArray(length=3) {
  return Array.from(Array(length).keys())
}

/**
 * 构建一个随机字符串    
 * @param {随机系数，系数越大，重复概率越低} length 
 * @returns 随机字符串
 */
function getuniqueID(length = 8) {
  if(length<=4){
    length=4
  }
  let solitCount =((length / 2)+1)>>0
  let firstPart = Math.random().toString().substring(3, 3+solitCount)
  let tempNow=Date.now().toString()
  let randomStart=tempNow.toString().length-( length-solitCount)
  let secondPart=tempNow.toString().substr((Math.random()*(randomStart+1)>>0),( length-solitCount))
  console.log(secondPart)
  let resultStr = firstPart+secondPart
  let resultArr = []
  if (resultStr.length > 11) {
    resultArr= buildArray(Math.ceil(resultStr.length/11)).reduce((pre, cur) => {
      pre.push(Number( resultStr.substring(cur * 11, (cur + 1) * 11)).toString(36))
      return pre
    }, [])
    resultStr = resultArr.join('')
  }else{
    resultStr= Number( resultStr).toString(36)
  }
  return resultStr
}

function getReallyLength(str) {
  var length = 0
  if (typeof str === 'string') {
    var tempstr = str.replace(/([\u4e00-\u9fa5])/g, 'aa')
    length = tempstr.length
  }
  return length
}

function subStr(str, num, endstr = '') {
  var tempstr = null
  if (typeof str === 'string') {
    var strlength = getReallyLength(str)
    if (typeof num === 'number') {
      if (strlength <= num) {
        tempstr = str
      } else {
        var reg = /[\u4e00-\u9fa5]/
        var tempnum = 0
        tempstr = ''
        for (const s of str) {
          ++tempnum
          if (reg.test(s)) {
            ++tempnum
          }
          if (tempnum <= num) {
            tempstr += s
          }
        }
      }
    }
  }
  tempstr = tempstr + endstr
  return tempstr
}
/**
 * 对象排序：使用方法 Array.sort(sortObj("key"))
 * @param {String} compareKye 比较对象中比较属性
 * @param {String} orderby 排序方式：asc 升序，desc 降序
 */
function sortObj(compareKye, orderby = 'asc') {
  return function(obja, objb) {
    const a = Number(obja[compareKye])
    const b = Number(objb[compareKye])
    if (orderby.toLowerCase() === 'desc') {
      if (a < b) return 1
      else if (a > b) return -1
      else return 0
    } else {
      if (a < b) return -1
      else if (a > b) return 1
      else return 0
    }
  }
}

/**
 * 数组去重,用法  distinct([1,2,3,1,3,5]);distinct([{a:24,b:1},{a:24,b:5},{a:21,b:18}],"a")
 * @param {Array} array 要去重的数组
 * @param {String} key 对象中的key
 */
function distinct(array, key) {
  if (array instanceof Array) {
    if (typeof array[0] == 'string' || typeof array[0] == 'number') {
      return Array.from(new Set(array))
    }
    return array.reduce((a, b) => {
      if (!a.some(aa => aa[key] == b[key])) {
        a.push(b)
      }
      return a
    }, [])
  }
}

/**
 *  数组分组，用法 groupBy([{a:24,b:1},{a:24,b:5},{a:21,b:18}],"a")
 * @param {Array} array 要分组的数组
 * @param {String} key 数组中对象的key
 */
function groupBy(array, key) {
  return array.reduce((a, b) => {
    var findItem = a.find(aa => aa.some(find => find[key] == b[key]))
    if (findItem) {
      findItem.push(b)
    } else {
      a.push([b])
    }
    return a
  },[])
}

/**
 *
 * @param {Function} fun 克隆的函数
 */
function funClone(fun) {
  let fct = fun
  let clone = function() {
    return fct.apply(this, arguments)
  }
  clone.prototype = fct.prototype
  for (let property in fct) {
    if ( property !== 'prototype') {
      clone[property] = fct[property]
    }
  }
  return clone
}

/**
 * http://www.abc.com/ggg?b=3&w=2
 * @param {String} httpurl httpurl
 */
function getHttpUrlParams(httpurl) {
  if (httpurl && httpurl.length > 0) {
    let codesStr = httpurl.substring(httpurl.lastIndexOf('?') + 1)
    if (codesStr) {
      let codes = codesStr.split('&')
      let codeobj = {}
      codes.forEach(a => {
        let tempcode = a.split('=')
        codeobj[tempcode[0]] = tempcode[1]
      })
      return codeobj
    }
  }
  return null
}

/**
 * 是null或者是""或者是{}或是undefined
 * @param {Object} obj
 */
function isReallyNull(obj) {
  let isReallyNull = false
  if (typeof obj === 'undefined') {
    isReallyNull = true
  }
  if (typeof obj === 'string') {
    if (obj.trim().length === 0) {
      isReallyNull = true
    }
  }
  if (typeof obj === 'object') {
    if (obj === null) {
      isReallyNull = true
    } else {
      isReallyNull = Object.keys(obj).length === 0
    }
  }
  return isReallyNull
}
/**
 *
 * @param {Array} tempArray  求和的数组
 * @param {String} key 数组item中的要求和的item.key
 * @returns {Number} 和
 */
function arraySum(tempArray, key = '') {
  let totalsum = 0
  let isobj = false
  if (key.trim().length > 0) {
    isobj = true
  }
  if (tempArray instanceof Array) {
    for (let index = 0; index < tempArray.length; index++) {
      let element
      if (isobj) {
        element = Number(tempArray[index][key])
      } else {
        element = Number(tempArray[index])
      }
      totalsum += element
    }
  }
  return totalsum
}

/**
 * 计算两个经纬度点之间的距离
 * @param {Number} lng1 第一个点的经度
 * @param {Number} lat1 第一个点的纬度
 * @param {Number} lng2 第二个点的经度
 * @param {Number} lat2 第二个点的纬度
 */
function calcDistance(lng1, lat1, lng2, lat2) {
  var radLat1 = (lat1 * Math.PI) / 180.0
  var radLat2 = (lat2 * Math.PI) / 180.0
  var a = radLat1 - radLat2
  var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
  var s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
  return s
}

function checkPhone(phone) {
  if (!/^1[3456789]\d{9}$/.test(phone)) {
    return false
  }
  return true
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
function debounce(func, wait, immediate) {
  let timeout
  return function() {
    const context = this
    const args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 */
function throttle(func, wait, type) {
  if (type === 1) {
    var previous = 0
  } else if (type === 2) {
    var timeout
  }
  return function() {
    const context = this
    const args = arguments
    if (type === 1) {
      const now = Date.now()

      if (now - previous > wait) {
        func.apply(context, args)
        previous = now
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null
          func.apply(context, args)
        }, wait)
      }
    }
  }
}

export {
  formatTime,
  formatLocation,
  dateUtils,
  getuniqueID,
  subStr,
  sortObj,
  isReallyNull,
  arraySum,
  debounce,
  throttle,
  checkPhone,
  calcDistance,
  distinct,
  groupBy,
  funClone,
  getHttpUrlParams
}
